package com.cssw.fyzb.core.dao.pay;

import com.cssw.fyzb.core.model.dodb.AcctTradeType;
import com.cssw.fyzb.core.model.dodb.BusiType;
import com.cssw.fyzb.core.model.dodb.UserPay;
import com.cssw.fyzb.core.model.dodb.UserPayH;
import com.cssw.fyzb.core.model.dodb.UserPayLog;
import com.cssw.fyzb.core.util.TimeUtil;
import com.ydn.dbframe.plugin.activerecord.Db;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @Author: chenchao
 * @Date: 2020/8/31 14:20
 */
@Repository
public class UserPayDaoImpl implements UserPayDao {

    @Override
    public void updateUserPay(Long userId, String tradeNo, String payType) {
        Db.tx(() -> {

            UserPay userPay = UserPay.dao.findById(userId);
            if (userPay != null) {

                addUserPayH(userPay, UserPayH.STATUS_FAIL);
                userPay.delete();
            }

            userPay = new UserPay();
            userPay.setUserId(userId);
            userPay.setTradeNo(tradeNo);
            userPay.setPayTime(new Date());
            userPay.setPayType(payType);
            userPay.save();
            return true;
        });
    }

    private void addUserPayH(UserPay userPay, String status) {
        UserPayH userPayH = new UserPayH();
        userPayH.setTradeNo(userPay.getTradeNo());
        userPayH.setUserId(userPay.getUserId());
        userPayH.setPayTime(userPay.getPayTime());
        userPayH.setCreateTime(new Date());
        userPayH.setPayType(userPay.getPayType());
        userPayH.setStatus(status);
        userPayH.save();
    }

    @Override
    public UserPay getUserPay(String tradeNo) {
        String sql = "select * from t_user_pay where trade_no =? ";
        return UserPay.dao.findFirst(sql, tradeNo);
    }

    @Override
    public UserPayH getUserPayH(String tradeNo) {
        return UserPayH.dao.findById(tradeNo);
    }

    @Override
    public void paySuccess(UserPay userPay) {
        addUserPayH(userPay, UserPayH.STATUS_SUCCESS);
        userPay.delete();
    }

    @Override
    public void savePayLog(Long userId, String payId, int payType, BigDecimal payFee) {
        UserPayLog userPayLog = new UserPayLog();
        userPayLog.setUserId(userId);
        userPayLog.setPayFee(payFee);
        userPayLog.setPayId(payId);
        userPayLog.setPayType(payType);
        userPayLog.setCreateTime(new Date());
        userPayLog.setTradeType(AcctTradeType.REAL_NAME_PAY);
        userPayLog.setBusiType(BusiType.REAL_NAME_PAY);
        Date now = new Date();
        userPayLog.setDayTime(TimeUtil.getTimeYYMMDD(now));
        userPayLog.setCreateTime(now);

        userPayLog.save();
    }


}
